package thread;

/**
 * Created with IntelliJ IDEA
 * Description：理解线程的中断命令
 * User：chenshu
 * Date：2023-11-02
 * Time：09:28
 */
public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            //Thread.interrupted();->读取后自动设置false
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("线程运行中");
                try {
                    //由sleep来抛出中断异常
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("线程3s后退出");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                }
            }
            System.out.println("新线程已经退出");
        });

        t.start();

        Thread.sleep(5000);
        System.out.println("控制线程退出");
        //中断的本质是请求t线程退出->线程是否结束由t线程自己决定
        //如果线程正在阻塞，则以异常方式通知，否则设置标志位
        t.interrupt();
    }
}
